
var toDiv = 5;// 5:friend
var gUrl = null;
var gInfo = gInfo;

$(function(){
    // 遮罩层
    //var maskCanv=document.getElementById('screen_mask');
    //var maskCanv2=document.getElementById('load_mask');

    $(".mask").addClass("disp_hide");
    $(".mask2").addClass("disp_hide");
    initUploader();
    redraw();
});

function onClickType(type){
    resetBtn();

    toDiv = Number(type);
    switch (toDiv){
        case 1:
            $(".btn_bf_sel").removeClass("disp_hide");
            $(".btn_bf").addClass("disp_hide");
            break;
        case 2:
            $(".btn_gf_sel").removeClass("disp_hide");
            $(".btn_gf").addClass("disp_hide");
            break;
        case 3:
            $(".btn_bro_sel").removeClass("disp_hide");
            $(".btn_bro").addClass("disp_hide");
            break;
        case 4:
            $(".btn_mi_sel").removeClass("disp_hide");
            $(".btn_mi").addClass("disp_hide");
            break;
        case 5:
            $(".btn_frid_sel").removeClass("disp_hide");
            $(".btn_frid").addClass("disp_hide");
            break;
        case 6:
            $(".btn_stud_sel").removeClass("disp_hide");
            $(".btn_stud").addClass("disp_hide");
            break;
        default :
            $(".btn_frid_sel").removeClass("disp_hide");
            $(".btn_frid").addClass("disp_hide");
    }
}

function resetBtn(){
    $(".btn_bro").removeClass("disp_hide");
    $(".btn_mi").removeClass("disp_hide");
    $(".btn_frid").removeClass("disp_hide");
    $(".btn_bf").removeClass("disp_hide");
    $(".btn_stud").removeClass("disp_hide");
    $(".btn_gf").removeClass("disp_hide");

    $(".btn_bro_sel").addClass("disp_hide");
    $(".btn_mi_sel").addClass("disp_hide");
    $(".btn_frid_sel").addClass("disp_hide");
    $(".btn_bf_sel").addClass("disp_hide");
    $(".btn_stud_sel").addClass("disp_hide");
    $(".btn_gf_sel").addClass("disp_hide");
}

function onClickVideo(){
    // TODO
}

function onClickApply(){

    $(".mask").removeClass("disp_hide");
    // 解析视频
    var postUrl = gInfo.api_host+'/home/typesetCard';
    var sendData = {
        type:toDiv,
        videoUrl:gUrl,
        name:$("#from_name").val()
    };
    $.post(postUrl, sendData, function(ret){
        $(".mask").addClass("disp_hide");
        if (ret.success == 1) {
            var newDocId = ret.data.doc_id;

            window.location.href= gInfo.api_host+'/preview/dispDoc?flg=1&tFlg=1&docId='+newDocId;
        } else {
            alert("哎呀，出错啦～ 麻烦重新尝试！");
        }
    });
}

var validFile = false;
var uploader = null;
function initUploader() {
    if (uploader) {
        return;
    }

    uploader = Qiniu.uploader({
        runtimes: 'html5,flash,html4',
        browse_button: 'btn_video',
        container: 'container',
        //drop_element: 'container',
        max_file_size: '10mb',
        //flash_swf_url: appPath + '/js/qiniu/plupload/Moxie.swf',
        dragdrop: false,
        //chunk_size: '5mb',
        //uptoken_url: appPath+"/itbImg/getUpToken.action",
        uptoken: gInfo.qn_token,
        domain: gInfo.qn_domain,
        // downtoken_url: '/downtoken',
        // unique_names: true,
        save_key: true,// 自定义文件名
        // x_vars: {
        //     'id': '1234',
        //     'time': function(up, file) {
        //         var time = (new Date()).getTime();
        //         // do something with 'time'
        //         return time;
        //     },
        // },
        auto_start: false,
        init: {
            'FilesAdded': function(up, files) {

                // reset
                gUrl = null;
                var vidDiv = document.getElementById('container');
                vidDiv.style.backgroundImage = 'url("")';
                $("#btn_video").removeClass("transparent");
                $(".btn_vid_frame").addClass("transparent");

                // check
                var fileCnt = up.files.length;
                if (fileCnt > 1) {
                    up.splice(0, fileCnt-1);
                }

                var fileName = up.files[0].name;
                //$('#imgFileNm').val(fileName);
                //if (Qiniu.isImage(fileName)) {
                if (isVideo(fileName)) {
                    validFile = true;
                    $(".mask2").removeClass("disp_hide");
                    up.start();
                } else {
                    validFile = false;
                    alert("请选择mp4或mov格式视频文件");
                }

                /*plupload.each(files, function(file) {
                 $('#imgFileNm').val(file.name);
                 var progress = new FileProgress(file, 'fsUploadProgress');
                 progress.setStatus("等待...");
                 progress.bindUploadCancel(up);
                 });*/
            },
            'BeforeUpload': function(up, file) {
                /*var progress = new FileProgress(file, 'fsUploadProgress');
                 var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                 if (up.runtime === 'html5' && chunk_size) {
                 progress.setChunkProgess(chunk_size);
                 }*/
            },
            'UploadProgress': function(up, file) {
                /* var progress = new FileProgress(file, 'fsUploadProgress');
                 var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                 progress.setProgress(file.percent + "%", file.speed, chunk_size);*/
            },
            'UploadComplete': function() {
                //$('#uploadMsg').show();
            },
            'FileUploaded': function(up, file, info) {
                $(".mask2").addClass("disp_hide");

                var retInfo = $.parseJSON(info);
                var fileNm = file.name;
                gUrl = gInfo.qn_domain+'/'+retInfo.key;
                var thumb = gUrl+"?vframe/jpg/offset/0.1/rotate/auto|imageView2/2/w/120/h/120";

                var vidDiv = document.getElementById('container');
                vidDiv.style.backgroundImage = "url("+thumb+")";
                $("#btn_video").addClass("transparent");
                $(".btn_vid_frame").removeClass("transparent");

                /*var progress = new FileProgress(file, 'fsUploadProgress');
                 progress.setComplete(up, info);*/

//                $.ajax('./uptoken',{
//                    async: false
//                }).done(function(data){
//                    $.extend(info, data);
//                    progress.setComplete(up, info);
//                }).error(function(){
//                    console.log('获取下载token失败');
//                });

            },
            'Error': function(up, err, errTip) {
                $(".mask2").addClass("disp_hide");
                gUrl = null;
                alert(errTip);

                //var progress = new FileProgress(err.file, 'fsUploadProgress');
                //progress.setError();
                //progress.setStatus(errTip);
            }
            // ,
            // 'Key': function(up, file) {
            //     var key = "";
            //     // do something with key
            //     return key
            // }
        }
    });
}


var resizeEnd;
function redraw() {
    if (resizeEnd) {
        clearTimeout(resizeEnd);
    }
    resizeEnd = setTimeout(function(){
        var vid = document.getElementById('btn_video');
        vid.width = vid.height;

        var app = document.getElementById('img_apply');
        app.width = app.height*2.62;

        var nm = document.getElementById('from_name');
        nm.style.fontSize = document.body.clientHeight/35+"px";

    },50);
}

// update on any window size change.
window.addEventListener("resize", redraw);

function isVideo(url) {
    var res, suffix = "";
    var videoSuffixes = ["mp4", "mov", "mpg"];
    var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;

    if (!url || !suffixMatch.test(url)) {
        return false;
    }
    res = suffixMatch.exec(url);
    suffix = res[1].toLowerCase();
    for (var i = 0, l = videoSuffixes.length; i < l; i++) {
        if (suffix === videoSuffixes[i]) {
            return true;
        }
    }
    return false;
};


wx.ready(function () {
    // 自定义分享内容及分享结果接口
    var myData = {
        title: '新春贺卡',
        desc: '来制作你的祝福贺卡吧～',
        link: gURL,
        imgUrl: 'http://7xogoq.com1.z0.glb.clouddn.com/itbserver/api/img/card/icon.jpg',
        trigger: function (res) {
            // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，
            // 因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回
            //alert('用户点击发送给朋友');
        },
        success: function (res) {
            alert('已分享');
        },
        cancel: function (res) {
            alert('已取消');
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    };

    // 监听“分享给朋友”
    wx.onMenuShareAppMessage(myData);
    // 监听“分享到朋友圈”
    wx.onMenuShareTimeline(myData);

});

wx.error(function (res) {
    //alert(res.errMsg);
});